//
//  NetService.m
//  quickBatchManager
//
//  Created by jack on 15/11/26.
//  Copyright © 2015年 jack. All rights reserved.
//

#import "NetService.h"
@interface NetService()

@property (nonatomic, retain) AFHTTPRequestOperationManager *manager;


@end
@implementation NetService


-(instancetype) init{
    self = [super init];
    if (self){
        
        NSString *urlString = BASE_URL;
        
        self.manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:urlString]];
        self.manager.securityPolicy.allowInvalidCertificates = YES;
        self.manager.securityPolicy.validatesCertificateChain = NO;
        self.manager.requestSerializer.timeoutInterval = 120.0;
      //
        //self.manager.requestSerializer = [AFHTTPRequestSerializer serializer];
       // self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        self.manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
      //  [self.manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    }
    
    return self;
}


//-(void)post:(NSString *)path params:(NSDictionary *)params success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success fail:(void (^)(AFHTTPRequestOperation *operation, NSError *error)) fail {
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        // 耗时的操作
//        
//        NSMutableDictionary *map = [NSMutableDictionary dictionaryWithDictionary:params];
//        NSString *url;
//        
//        if([path hasPrefix:@"http://"])
//        {
//            url=path;
//        }
//        else
//        {
//            url=[NSString stringWithFormat:@"%@/%@",PREFIX_URL,path];
// 
//        }
//        
//        NSLog(@"params:%@",map);
//        [self.manager POST:url parameters:map success:^(AFHTTPRequestOperation *operation, id responseObject){
//            NSLog(@"response:%@",responseObject);
//            
//            long code = [NetService getStatusCode:responseObject];
//            if (code ==200){
//                
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    if (success){
//                        success(operation, responseObject);
//                    }
//                });
//            }
//        } failure:^(AFHTTPRequestOperation *operation, NSError *error){
//            dispatch_async(dispatch_get_main_queue(), ^{
//                if (fail){
//                    fail(operation, [self parseError:error]);
//                }
//            });
//        }];
//        
//    });
//}


-(void) post:(NSString*) path params:(NSDictionary *)params success:(void (^)(AFHTTPRequestOperation *operation, id responseObject)) success fail:(void (^)(AFHTTPRequestOperation *operation, NSError *error)) fail
{
    
    NSMutableDictionary *map = [NSMutableDictionary dictionaryWithDictionary:params];
    NSString *url;
    
    if([path hasPrefix:@"http://"])
    {
        url=path;
    }
    else
    {
        url=[NSString stringWithFormat:@"%@/%@",PREFIX_URL,path];
        
    }
    
    NSLog(@"params:%@",map);
      NSLog(@"url:%@",url);
    [self.manager POST:url parameters:map success:^(AFHTTPRequestOperation *operation, id responseObject){
        NSLog(@"response:%@",responseObject);
        
        long code = [NetService getStatusCode:responseObject];
        if (code ==200){
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (success){
                    success(operation, responseObject);
                }
            });
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error){
        dispatch_async(dispatch_get_main_queue(), ^{
            if (fail){
                fail(operation, [self parseError:error]);
            }
        });
    }]; 
}

-(void)post:(NSString *)path params:(NSDictionary *)params filedName:(NSString*)filedName imageName:(NSString *)imageName image:(UIImage*)image success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success fail:(void (^)(AFHTTPRequestOperation *operation, NSError *error)) fail
{
    // 耗时的操作
    NSMutableDictionary *map = [NSMutableDictionary dictionaryWithDictionary:params];
    NSString *url;
    
    if([path hasPrefix:@"http://"])
    {
        url=path;
    }
    else
    {
        url=[NSString stringWithFormat:@"%@/%@",PREFIX_URL,path];
        
    }
    
    [self.manager POST:url parameters:map constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        if(image!=nil){
                NSData *imageData = UIImageJPEGRepresentation(image,0.5);
                [formData appendPartWithFileData:imageData name:filedName
                                        fileName:imageName
                                        mimeType:@"image/png"];
        }
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"%@",responseObject);
        long code = [NetService getStatusCode:responseObject];
        
        if (code ==200){
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (success){
                    success(operation, responseObject);
                }
            });
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (fail){
                fail(operation, [self parseError:error]);
            }
        });
    }];
}


-(void)post:(NSString *)path params:(NSDictionary *)params filedName:(NSString*)filedName dataName:(NSString *)dataName data:(NSData*)data success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success fail:(void (^)(AFHTTPRequestOperation *operation, NSError *error)) fail
{
    // 耗时的操作
    NSMutableDictionary *map = [NSMutableDictionary dictionaryWithDictionary:params];
    NSString *url;
    
    if([path hasPrefix:@"http://"])
    {
        url=path;
    }
    else
    {
        url=[NSString stringWithFormat:@"%@/%@",PREFIX_URL,path];
        
    }
    
    [self.manager POST:url parameters:map constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        if(data!=nil){
            [formData appendPartWithFileData:data name:filedName
                                    fileName:dataName
                                    mimeType:@"application/zip"];
        }
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"%@",responseObject);
        long code = [NetService getStatusCode:responseObject];
        
        if (code ==200){
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (success){
                    success(operation, responseObject);
                }
            });
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (fail){
                fail(operation, [self parseError:error]);
            }
        });
    }];
}


-(void)post:(NSString *)path params:(NSDictionary *)params filedName:(NSString*)filedName images:(NSArray*)images success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success fail:(void (^)(AFHTTPRequestOperation *operation, NSError *error)) fail {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 耗时的操作
        NSMutableDictionary *map = [NSMutableDictionary dictionaryWithDictionary:params];
        NSString *url;
        
        if([path hasPrefix:@"http://"])
        {
            url=path;
        }
        else
        {
            url=[NSString stringWithFormat:@"%@/%@",PREFIX_URL,path];
            
        }
        
        [self.manager POST:url parameters:map constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            if(images!=nil){
                for(UIImage *eachImage in images){
                    NSData *imageData = UIImageJPEGRepresentation(eachImage,0.5);
                    long time = (long)[[NSDate date] timeIntervalSince1970] *1000;
                    [formData appendPartWithFileData:imageData name:filedName
                                            fileName:[NSString stringWithFormat:@"abc%ld.jpg",time ]
                                            mimeType:@"image/png"];
                }
            }
            
        } success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"%@",responseObject);
            long code = [NetService getStatusCode:responseObject];
            
            if (code ==200){
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (success){
                        success(operation, responseObject);
                    }
                });
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (fail){
                    fail(operation, [self parseError:error]);
                }
            });
        }];
    });
    
}


//状态验证
-(BOOL)codeVail:(long)code
{
    if(code!=200)
    {
        return NO;
    }
    
    return YES;
}

+(NSInteger) getStatusCode:(id)response{
    NSInteger statusCode = -1;
    if (response && [response objectForKey:@"code"]) {
        statusCode = [[response objectForKey:@"code"] integerValue];
    }
    return statusCode;
}

+(NSString *) getMessage:(id)response{
    return [response objectForKey:@"errorMsg"];
}

+(id) getBody:(id)response{
    return [response objectForKey:@"body"];
}

+(id) getBodyForKey:(NSString*)key andData:(id)response;
{
    NSDictionary *body=[self getBody:response];
    if(![body isEqual:[NSNull null]])
        return [body objectForKey:key];
    else return nil;
}

-(NSError*)parseError:(NSError*)error
{
    
    NSString *errorMessage=@"";
    
    switch (error.code) {
        case NSURLErrorTimedOut:
            errorMessage=@"亲，网络在开小差，请稍后再试";
            break;
        case NSURLErrorCannotConnectToHost:
        case NSURLErrorNetworkConnectionLost:
        case NSURLErrorDNSLookupFailed:
        case NSURLErrorNotConnectedToInternet:
            errorMessage=@"网络请求失败，请检查您的网络设置";
            break;
        default:
            errorMessage=@"亲，您的手机网络不太顺畅哦，请稍后再试";
            break;
    }
    
    NSError *neterror = [NSError errorWithDomain:errorMessage code:error.code userInfo:nil];
    
    
    return neterror;
}


-(void)stopAllOperations
{
    [self.manager.operationQueue cancelAllOperations];
}

@end
